<script setup lang="ts">
import {reactive, onMounted, nextTick, ref} from 'vue';
import {
  deleteBannerList,
  deletePriceList,
  deleteTagList,
  getPriceList,
  getTagList,
  postBannerList, postPriceList,
  postTagList
} from '/@/api/api'
import {ElMessage} from 'element-plus';
const avueFormRes = ref()
const data = reactive({
  title:'Add',
  dialogShow: false,
  tabIndex: 0,
  dataList: [],
  page: {
    total: 10,
    currentPage: 1,
    pageSize: 10,
  },
  option: {
    searchLabelWidth: 50,
    addBtn: false,
    printBtn: false,
    excelBtn: false,
    // searchSpan: 5,
    searchMenuSpan: 4,
    border: true,
    viewBtn: false,
    editBtn: false,
    delBtn: false,
    align: 'center',
    column: [
      {
        label: 'Creation time',
        prop: 'createTime',
      },
      {
        label: 'Price name',
        prop: 'priceName',
      },
      {
        label: 'Price money',
        prop: 'priceMoney',
      },
    ]
  },
  optionForm: {
    submitText:'Submit',
    emptyText	:'Empty',
    column: [
      {
        label: 'Price name',
        labelWidth:120,
        span: 24,
        prop: 'priceName',
        type: 'input',
        rules: [
          {
            required: true,
            message: "Please enter the Price name",
            trigger: "blur"
          }
        ]
      },
      {
        label: 'Price money',
        span: 24,
        prop: 'priceMoney',
        type: 'input',
        labelWidth:120,
        rules: [
          {
            required: true,
            message: "Please enter the correct price",
            trigger: "blur"
          }
        ]
      },
      {
        label: 'Sort',
        labelWidth:120,
        span: 24,
        prop: 'sort',
        type: 'number',
      },
    ]
  },
  form: {
    priceName:'',
    priceMoney:'',
    priceMoney1:'',
    priceMoney2:'',
    priceId:'',
    sort:0
  },
})

onMounted(() => {

})
const bannerList = () => {
  let page = {
    pageIndex: data.page.currentPage,
    pageSize: data.page.pageSize
  }
  getPriceList(page).then((res: any) => {
    if (res.code === 200) {
      data.dataList = res.data.list
      data.page.total = res.data.total
    }
  })
}
const parsePriceRange = (priceRangeStr: string): [number | null, number | null] => {
  const priceParts = priceRangeStr.replace(/[$]/g, '').split('-');
  if (priceParts.length === 1) {
    const singlePrice = parseFloat(priceParts[0]);
    return [singlePrice, null];
  } else if (priceParts.length === 2) {
    const lowerBound = parseFloat(priceParts[0]);
    const upperBound = parseFloat(priceParts[1]);
    return [lowerBound, upperBound];
  } else {
    throw new Error('Invalid price range format');
  }
}
const editCarousel = (row:any) => {
  data.dialogShow = true
  data.form.priceName = row.priceName
  data.form.sort = row.sort
  data.form.priceMoney = row.priceMoney
  data.form.priceMoney1 = '$'+Number(parsePriceRange(row.priceMoney)[0]).toFixed(2)
  data.form.priceMoney2 = parsePriceRange(row.priceMoney)[1] ? '$'+Number(parsePriceRange(row.priceMoney)[1]).toFixed(2) : ''
  data.form.priceId = row.priceId
}

const addCarousel = () => {
  data.title = 'Add to'
  data.dialogShow = true
  data.form.priceMoney1 = ''
  data.form.priceMoney2 = ''
  nextTick(()=>{
    avueFormRes.value.resetForm()
  })
}
const onLoad = (e:any) => {
  console.log(e)
  data.page.currentPage = e.currentPage
  data.page.pageSize = e.pageSize
  bannerList()
}
const refreshChange = () => {
  bannerList()
}
const handleReset = (form:any, done:any) => {
  data.form.priceMoney1 = ''
  data.form.priceMoney2 = ''
}
const deleteCarousel = (row:any) => {
  deletePriceList({priceId:row.priceId}).then((res: any) => {
    bannerList()
    if (res.code === 200) {
      ElMessage({
        showClose: true,
        message: 'The deletion is successful',
        type: 'success',
      })
    }
  })
}
const handleSubmit = (form: object, done: any) => {
  if (data.form.priceMoney1 === ''){
    return
  }
  let forms = {
    priceName:data.form.priceName,
    priceMoney:data.form.priceMoney,
    sort:data.form.sort,
    priceId:data.form.priceId
  }
  postPriceList({...forms}).then((res: any) => {
    done()
    bannerList()
    data.form.priceId = ''
    if (res.code === 200) {
      ElMessage({
        showClose: true,
        message: 'The addition was successful',
        type: 'success',
      })
      data.dialogShow = false
    }
  })
}
const LowestPriceFun = (e:any) => {
  console.log(e)
  if (compareNubFun()){
    if (data.form.priceMoney2 === '' || data.form.priceMoney1 === '$'){
      data.form.priceMoney = data.form.priceMoney1
    } else {
      data.form.priceMoney = data.form.priceMoney1 + ' - ' + data.form.priceMoney2
    }
  }
}
const compareNubFun = () => {
  const num1 = Number(parseFloat(data.form.priceMoney1.replace(/[$,]/g, "")).toFixed(2))
  const num2 = Number(parseFloat(data.form.priceMoney2.replace(/[$,]/g, "")).toFixed(2))
  if (num1 >= num2) {
    if (num1 > num2){
      ElMessage({
        showClose: true,
        message: 'The highest price must be greater than the lowest price',
        type: 'warning',
      })
    }
    return false
  }
  if (data.form.priceMoney1 === ''){
    ElMessage({
      showClose: true,
      message: 'Please enter the price range',
      type: 'warning',
    })
    return false
  }
  else {
    return true
  }
}
</script>

<template>
  <div class="layout-pd">
    <div class="carousel-box">
      <avue-crud v-model:page="data.page" :data="data.dataList" :option="data.option" @on-load="onLoad" @refresh-change="refreshChange">
        <template #menu-left="{}">
          <el-button type="success" @click="addCarousel">New</el-button>
        </template>
        <template #menu="{row}">
          <el-button text type="primary" @click="editCarousel(row)">Edit</el-button>
          <el-button text type="primary" @click="deleteCarousel(row)">Delete</el-button>
<!--          <el-button text type="primary" @click="deleteCarousel(row)">Edit</el-button>-->
        </template>
      </avue-crud>
    </div>
    <el-dialog
        v-model="data.dialogShow"
        :title="data.title"
        width="50%"
    >
      <avue-form ref="avueFormRes" :option="data.optionForm" v-model="data.form" @submit="handleSubmit"  @reset-change="handleReset">
        <template #priceMoney="{disabled,size}">
          <div style="display: flex">
            <el-input v-model="data.form.priceMoney1" :disabled="disabled" :size="size" type="text"
                      :formatter="(value) => `$${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                      :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
                      placeholder="Please enter the Lowest price"
                      @change="LowestPriceFun"
            />
            <div>——</div>
            <el-input v-model="data.form.priceMoney2" :disabled="disabled" :size="size" type="text"
                      :formatter="(value) => `$${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                      :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
                      placeholder="Please enter the Highest price"
                      @change="LowestPriceFun"
            />
          </div>
        </template>
      </avue-form>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.carousel-box {
  width: 100%;
  box-sizing: border-box;
  background: var(--el-color-white);
  padding: 20px;
}

.item-img {
  width: 100%;

  img {
    width: 50%;
  }
}

::v-deep .avue-form__row {
  margin-bottom: 20px;
}
::v-deep .el-select {
  width: 100% !important;
}
</style>